package org.hcyspartnoc.luoxin.utils;

import cn.hutool.core.util.StrUtil;
import io.netty.channel.Channel;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ChannelContextUtils {
    // 用户连接通道 一个id可对应多个通道
    private static final ConcurrentHashMap<String, DefaultChannelGroup> USER_CHANNEL_GROUPS = new ConcurrentHashMap<>();


    public void addUid(String uid, Channel channel) {
        if (Objects.isNull(channel) || StrUtil.isBlank(uid))
            return;
        AttributeKey<String> key;
        String channelId = channel.id().toString();
        if (!AttributeKey.exists(channelId))
            key = AttributeKey.newInstance(channelId);
        else
            key = AttributeKey.valueOf(channelId);
        channel.attr(key).set(uid);
        // 将当前用户添加至用户连接通道
        attachToGroups(channel, uid);

    }

    public String getUid(Channel channel) {
        return (String) channel.attr(AttributeKey.valueOf(channel.id().toString())).get();
    }

    public void attachToGroups(Channel channel, String uid) {
        if (Objects.isNull(channel) || StrUtil.isBlank(uid))
            return;
        if (!USER_CHANNEL_GROUPS.containsKey(uid))
            USER_CHANNEL_GROUPS.put(uid, new DefaultChannelGroup(GlobalEventExecutor.INSTANCE));
        USER_CHANNEL_GROUPS.get(uid).add(channel);
    }

    public void detachFromGroups(Channel channel, String uid) {
        if (Objects.isNull(channel) || StrUtil.isBlank(uid))
            return;
        if (USER_CHANNEL_GROUPS.containsKey(uid)) {
            USER_CHANNEL_GROUPS.get(uid).remove(channel);
            if (USER_CHANNEL_GROUPS.get(uid).isEmpty())
                USER_CHANNEL_GROUPS.remove(uid);
        }
    }

    public void removeFromGroups(String uid) {
        if (Objects.isNull(uid))
            return;
        USER_CHANNEL_GROUPS.remove(uid);
    }

    public void sendToUser(String uid, String text) {
        if (USER_CHANNEL_GROUPS.containsKey(uid))
            USER_CHANNEL_GROUPS.get(uid).writeAndFlush(new TextWebSocketFrame(text));
    }

}
